// pages/home/home.js
import { getStorageItem } from "../../utils/storage";
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import { userStore } from "@/stores/user-store";

const app = getApp();
Page({
  behaviors: [storeBindingsBehavior],
  storeBindings: {
    store: userStore,
    fields: ["userInfo"],
    actions: ["getUserInfo"],
  },
  /**
   * 页面的初始数据
   */
  data: {
    token: getStorageItem("token"),
    invite_pcount: 0,
    vip_grade: 0,
    vip_point: 0,
    user_money: {
      earning_total: 0,
    },
    vipData: {
      needGrade: 1,
      title: "青铜会员",
      desc: "所有功能免费使用",
    },
    registerIsHidden: true,
    masklayer: false,
    comment_size: 0,
    userName: "",
    userAvatar: "",
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const userAvatar = getStorageItem("headerImgPath");
    const userName = getStorageItem("user_name");
    const commonData = {
      userName,
      userAvatar,
    };
    if (!getApp().globalData.token) {
      this.setData({
        ...commonData,
      });
      return;
    }
    let vipData = getStorageItem("vipData");
    let vip_point = getStorageItem("vip_point");
    let percent =
      (parseFloat(vip_point) /
        (parseFloat(vip_point) + parseFloat(vipData.needGrade))) *
      100;

    this.setData({
      ...commonData,
      invite_pcount: getStorageItem("invite_pcount"),
      vip_grade: getStorageItem("vip_grade"),
      vip_point,
      user_money: getStorageItem("user_money"),
      vipData,
      percent,
      comment_size: getStorageItem("comment_size"),
      reserveCount: getStorageItem("reserveCount"),
      token: getStorageItem("token"),
    });

    this.checkAndGetUserInfo();
  },
  toVip() {
    if (this.data.userInfo.isShowNewMembership) {
      wx.navigateTo({
        url: "/subpkg/pages/membership-levels/membership-levels",
      });
      return;
    }

    wx.navigateTo({
      url: "/pages/home/vip/vip",
    });
  },
  turnToInfoPage() {
    wx.navigateTo({
      url: "/pages/home/editInfo/editInfo",
    });
  },
  /** 检查并获取数据 */
  async checkAndGetUserInfo() {
    let taskList = [];
    if (!this.data.userInfo.id) {
      taskList.push(this.getUserInfo());
    }
    await Promise.all(taskList);
    this.updateStoreBindings();
  },
});
